package com.didispace.chapter44;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class UploadController {

    private final String separator = System.getProperty("file.separator");

    private final PathManager pathManager;

    public UploadController(PathManager pathManager) {
        this.pathManager = pathManager;
    }

    @GetMapping("/")
    public String uploadPage() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> create(@RequestParam CommonsMultipartFile[] files, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        StringBuilder message = new StringBuilder();
//        Progress status = (Progress) session.getAttribute("status");
//        List<String> collect = Arrays.stream(files).map(CommonsMultipartFile::getOriginalFilename).collect(Collectors.toList());
//        status.setName(collect);
        String fileAbsolutePath = "";
        try {
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue;
                }
                String fileName = file.getOriginalFilename();
                String filePath = pathManager.getPath() + separator + fileName;

                File dest = new File(filePath);
                fileAbsolutePath = dest.getAbsolutePath();
                if (dest.exists() && dest.isFile()) {
                    dest.delete();
                }
                Files.copy(file.getInputStream(), dest.toPath());

                message.append("Upload file success : ")
                        .append(fileAbsolutePath)
                        .append("<br>");
                result.put("tag", true);
            }
        } catch (Exception e) {
            message.append("Upload file fail : ")
                    .append(fileAbsolutePath)
                    .append("<br>");
            result.put("tag", false);
        }
        result.put("message", message.toString());
        return result;
    }

    @ResponseBody
    @GetMapping("/getInfo")
    public Map<String, Object> getUploadInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        response.setHeader("Cache-Control", "no-store"); //禁止浏览器缓存
        response.setHeader("Pragrma", "no-cache");  //禁止浏览器缓存
        response.setDateHeader("Expires", 0);   //禁止浏览器缓存

        Progress status = (Progress) request.getSession(true).getAttribute("status");//从session中读取上传信息
        if (status == null) {
            result.put("error", "没发现上传文件!");
            return result;
        }

        long startTime = status.getStartTime();  //上传开始时间
        long currentTime = System.currentTimeMillis(); //现在时间
        long time = (currentTime - startTime) / 1000 + 1;//已经传顺的时间 单位：s
        double velocity = status.getBytesRead() / time; //传输速度：byte/s
        double totalTime = status.getContentLength() / velocity; //估计总时间
        double timeLeft = totalTime - time;    //估计剩余时间
        int percent = (int) (100 * (double) status.getBytesRead() / (double) status.getContentLength()); //百分比
        double length = status.getBytesRead() / 1024 / 1024; //已完成数
        double totalLength = status.getContentLength() / 1024 / 1024; //总长度  M

        result.put("startTime", startTime);
        result.put("currentTime", currentTime);
        result.put("time", time);
        result.put("velocity", velocity);
        result.put("totalTime", totalTime);
        result.put("timeLeft", timeLeft);
        result.put("percent", percent);
        result.put("length", length);
        result.put("totalLength", totalLength);
        result.put("name", status.getName());
        result.put("items", status.getItems());
        return result;
    }

}